import 'dart:convert';
import 'package:get/get.dart';
import 'package:hao/utils/HaoModel.dart';
import 'package:hao/utils/RecordModel.dart';
import 'package:shared_preferences/shared_preferences.dart';

class HomeViewModel extends GetxController {
  final list = [].obs;
  final allList = [];
  final isLoading = true.obs;

  @override
  void onInit() {
    super.onInit();
    loadData();
  }

  void loadData() async {
    // BmobWhereBuilder _where = BmobWhereBuilder();
    // BmobQueryHelper.query<Hao, dynamic>(Hao(), (json) => Hao().fromJson(json),
    //         where: _where)
    //     .then((value) {
    //   isLoading.value = false;
    //   List results = value.results;
    //   allList.assignAll(results);
    //   dealList();
    // });

    isLoading.value = false;
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    String str = sharedPreferences.getString("list") ?? "[]";
    List _list = json.decode(str);
    List models = [];
    for (Map<String,dynamic> map in _list) {
      Record record = Record.fromJson(map);
      models.add(record);
    }
    allList.assignAll(models);
    dealList();
  }

  void dealList() {
    if (allList.isNotEmpty && allList.length > 1) {
      allList.sort((chu1, chu2) {
        String time1 = (chu1 as Record).expire ?? "";
        String time2 = (chu2 as Record).expire ?? "";
        int interval1 = DateTime.parse(time1).millisecondsSinceEpoch;
        int interval2 = DateTime.parse(time2).millisecondsSinceEpoch;
        if (interval1 > interval2) {
          return -1;
        }
        return 1;
      });
    }

    Map map = {};
    for (Record chu in allList) {
      String time = chu.time ?? "";
      DateTime dateTime = DateTime.parse(time);
      String month = dateTime.month.toString();
      if (map[month] == null) {
        map[month] = [chu];
      } else {
        List cc = map[month];
        cc.add(chu);
        map[month] = cc;
      }
    }

    List _list = [];
    for (String key in map.keys) {
      Map ret = {"month": key, "datas": map[key]};
      _list.add(ret);
    }

    _list.sort((map1, map2) {
      int month1 = int.parse(map1["month"]);
      int month2 = int.parse(map2["month"]);
      if (month1 > month2) {
        return -1;
      }
      return 1;
    });

    list.assignAll(_list);
  }
}
